/**
 * 
 */
package com.sahyadri.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sahyadri.web.bean.User;
import com.sahyadri.web.util.constant.SessionAttributeKeys;
import com.sahyadri.web.util.security.UserHolder;

/**
 * Controller handles requests related to user authentication and password management.
 * 
 * @author Mohan
 */
@Controller
public class AuthenticationController {

	private static final Logger log = Logger.getLogger(AuthenticationController.class);
	private static final String QUERY_STRING_KEY_REASON = "reason";
	private UserHolder userHolder;
	
	@Autowired
	public void setUserHolder(UserHolder userHolder) {
		this.userHolder = userHolder;
	}

	/**
	 * Entry point into sahyadri-web system. This method performs required session initialization checks such as
	 * determining if this is the users first login.
	 * 
	 * @param session
	 *            Completion of initSession process is flagged in HttpSession so that SessionInitFilter can
	 *            redirect any users here that haven't completed this process. If all init session checks pass,
	 *            flag in session should be set accordingly.
	 * 
	 * @return Depending on checks made against the current user, different redirect urls will be returned.
	 *         <ul>
	 *         <li>If this is the users first time logging in, they are redirected to the first time login page
	 *         </ul>
	 */
	@RequestMapping(value = "/authentication/initSession", method = RequestMethod.GET)
	public String initSession(HttpSession session) {
		User user = userHolder.getUser();
		String loginId = user.getUsername();
		log.debug("entered initSession for user: " + loginId + ".");
		session.setAttribute(SessionAttributeKeys.INIT_SESSION_FLAG, Boolean.TRUE);
		
		return "redirect:/rest/admin/landing";

	}

	/**
	 * Handles the logout requests for Single Sign-on
	 * 
	 * @return
	 */
	@RequestMapping(value = "/public/authentication/logout")
	public String setupLogout(HttpServletRequest request,
			@RequestParam(value = QUERY_STRING_KEY_REASON, required = false) String logoutReason,
			@RequestParam(value = "userName", required = false) String userName, ModelMap model) {
		
		log.debug("Entered logout() method. userName:" + userName);
		SecurityContextHolder.getContext().setAuthentication(null);
		request.getSession().invalidate(); 
		return "redirect:/rest/public/home";
		
	}
}
